import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { CartItem } from './types/product';
import './Cart.css';
import Layout from './Layout';

const Cart = () => {
    const navigate = useNavigate();
    const [cartItems, setCartItems] = useState<CartItem[]>([]);

    useEffect(() => {
        // 从localStorage获取购物车数据
        const items = JSON.parse(localStorage.getItem('cartItems') || '[]');
        setCartItems(items);
    }, []);

    const handleQuantityChange = (itemId: string, newQuantity: number) => {
        if (newQuantity < 1) return;

        const updatedItems = cartItems.map(item =>
            item.id === itemId ? { ...item, quantity: newQuantity } : item
        );

        setCartItems(updatedItems);
        localStorage.setItem('cartItems', JSON.stringify(updatedItems));
    };

    const handleDelete = (itemId: string) => {
        const updatedItems = cartItems.filter(item => item.id !== itemId);
        setCartItems(updatedItems);
        localStorage.setItem('cartItems', JSON.stringify(updatedItems));
    };

    const calculateTotal = () => {
        return cartItems.reduce((total, item) => {
            let itemTotal = item.price * item.quantity;

            // 添加服务费用
            item.selectedServices.forEach(serviceId => {
                const service = item.services.find(s => s.id === serviceId);
                if (service) itemTotal += service.price * item.quantity;
            });

            // 添加配件费用
            item.selectedAccessories.forEach(accessoryId => {
                const accessory = item.accessories.find(a => a.id === accessoryId);
                if (accessory) itemTotal += accessory.price * item.quantity;
            });

            return total + itemTotal;
        }, 0);
    };

    const handleCheckout = () => {
        // 将购物车商品转移到订单
        localStorage.setItem('currentOrder', JSON.stringify(cartItems));
        // 清空购物车
        localStorage.setItem('cartItems', '[]');
        // 跳转到订单确认页面
        navigate('/order-confirm');
    };

    if (cartItems.length === 0) {
        return (
            <Layout>
                <div className="cart-empty">
                    <h2>购物车是空的</h2>
                    <button onClick={() => navigate('/shopping')}>去购物</button>
                </div>
            </Layout>
        );
    }

    return (
        <Layout>
            <div className="cart">
                <h2>购物车</h2>
                <div className="cart-items">
                    {cartItems.map(item => (
                        <div key={item.id} className="cart-item">
                            <img src={item.images[0]} alt={item.name} className="item-image" />
                            <div className="item-info">
                                <h3>{item.name}</h3>
                                <p className="specs">
                                    {item.selectedSpecs.color && `颜色：${item.selectedSpecs.color}`}
                                    {item.selectedSpecs.storage && ` 存储：${item.selectedSpecs.storage}`}
                                </p>
                                <div className="services">
                                    {item.selectedServices.map(serviceId => {
                                        const service = item.services.find(s => s.id === serviceId);
                                        return service && (
                                            <span key={service.id} className="service-tag">
                                                {service.name}
                                            </span>
                                        );
                                    })}
                                </div>
                                <div className="accessories">
                                    {item.selectedAccessories.map(accessoryId => {
                                        const accessory = item.accessories.find(a => a.id === accessoryId);
                                        return accessory && (
                                            <span key={accessory.id} className="accessory-tag">
                                                {accessory.name}
                                            </span>
                                        );
                                    })}
                                </div>
                            </div>
                            <div className="item-price">¥{item.price}</div>
                            <div className="quantity-controls">
                                <button
                                    onClick={() => handleQuantityChange(item.id, item.quantity - 1)}
                                    disabled={item.quantity <= 1}
                                >
                                    -
                                </button>
                                <span>{item.quantity}</span>
                                <button
                                    onClick={() => handleQuantityChange(item.id, item.quantity + 1)}
                                >
                                    +
                                </button>
                            </div>
                            <div className="item-total">
                                ¥{calculateTotal() * item.quantity}
                            </div>
                            <button
                                className="delete-btn"
                                onClick={() => handleDelete(item.id)}
                            >
                                删除
                            </button>
                        </div>
                    ))}
                </div>
                <div className="cart-summary">
                    <div className="total">
                        总计：¥{calculateTotal()}
                    </div>
                    <button
                        className="checkout-btn"
                        onClick={handleCheckout}
                    >
                        去结算
                    </button>
                </div>
            </div>
        </Layout>
    );
};

export default Cart; 